package com.ldd.mybatis.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ldd.mybatis.mapper.EmpMapper;
import com.ldd.mybatis.model.Emp;
import com.ldd.mybatis.model.MyApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @项目名： spring-emq
 * @包名： com.ldd.mybatis.service.impl
 * @文件名: SqlSessionFactoryImpl
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/12 21:07
 * @描述：
 */
@Slf4j
@Service
public class SqlSessionFactoryImpl {
    @Autowired
    private SqlSessionFactory sqlSessionFactory;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private EmpServiceImpl2 empService;

    public MyApiResponse<List<Emp>> getEmp() throws JsonProcessingException {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> emps = empMapper.empList();
        log.info("testSqlSessionFactory: {}", objectMapper.writeValueAsString(emps));
//        sqlSession.clearCache();//一级缓存是默认开启的，是不能关闭的，但可以调用SqlSession的clearCache()方法清理缓存；
        int i = empMapper.insertValues();
//        int i2 = empMapper.insertEmp();
        Emp emp = emps.get(i);
        emp.setEName("" + System.currentTimeMillis());
        Emp emp2 = empService.insertEmp2(emp);
        log.info("insertValues: {}", objectMapper.writeValueAsString(i));
        log.info("insertValues2 : {}", objectMapper.writeValueAsString(emp2));
//        log.info("insertValues3 : {}", objectMapper.writeValueAsString(i2));
        EmpMapper empMapper2 = sqlSession.getMapper(EmpMapper.class);
        List<Emp> emps2 = empMapper2.empList();
        log.info("testSqlSessionFactory2: {}", objectMapper.writeValueAsString(emps2));
        return MyApiResponse.success(emps);
    }
}
